package com.kanshu.ksgb.fastread.doudou.module.makemoney.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.event.TaskEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.bean.AutoReceiveBean;
import com.kanshu.ksgb.fastread.doudou.module.makemoney.presenter.MakeMoneyPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by wcy on 18/5/29
 */

public class TimerManager {
    private static final int MAX_MIN = 10;
    private static final int VALIDE_READ_MINS = MAX_MIN * 60 * 1000;
    public static final int MIN_PAGE = 20;
    public static final int MAX_PAGE = 120;
    private static TimerManager sInstance;
    private static final String CONFIG_NAME = "timer_config";
    private static final String KEY_PAGE_COUNT = "page_count";
    private Timer mTimer;
    private TimerTask mTimerTask;
    private boolean mStart;
    private MakeMoneyPresenter mPresenter;
    private SharedPreferences mSharedPreferences;
    private boolean mSettingConfig;

    public static TimerManager getInstance() {
        synchronized (TimerManager.class) {
            if (sInstance == null) {
                sInstance = new TimerManager();
            }
        }
        return sInstance;
    }

    private TimerManager() {
        mSettingConfig = Xutils.getContext().getResources().getBoolean(R.bool.timer_read_setting_config);
        mPresenter = new MakeMoneyPresenter(null);
        mSharedPreferences = Xutils.getContext().getSharedPreferences(CONFIG_NAME, Context.MODE_PRIVATE);
        mTimer = new Timer(CONFIG_NAME, true);
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                AndroidSchedulers.mainThread().scheduleDirect(() -> {
                    upload();
                });
            }
        };
    }

    /**
     * 上报数据
     */
    private void upload() {
        int page = mSharedPreferences.getInt(KEY_PAGE_COUNT + "#" + UserUtils.getUserId(), 0);
        // 用户没有登录状态  或者 20 - 120页之间 才算一次有效10分钟时间
        if(MMKVUserManager.getInstance().getLoginState() != Constants.LoginState.TYPE_HAS_LOGIN || page < MIN_PAGE || page > MAX_PAGE){
            if (mSettingConfig) {
                AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showStaticMessage("当前的阅读页数:" + page + "无效的十分钟阅读记录,此时不会上报后台，这个十分钟是无效的！！！！");
                    }
                });
            }
            reset();
        } else {
            // 上报数据给后台
            if (mSettingConfig) {
                AndroidSchedulers.mainThread().scheduleDirect(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.showStaticMessage("开始上报数据，当前读的页数在20-120之间！！！！！！");
                    }
                });
            }
            AndroidSchedulers.mainThread().scheduleDirect(() ->mPresenter.uploadReadTime(MAX_MIN, new INetCommCallback<Boolean>() {
                @Override
                public void onResponse(Boolean f) {
                    if (f) {
                        reset();
                        TaskEvent event = new TaskEvent();
                        EventBus.getDefault().post(event);
                        if (mSettingConfig) {
                            ToastUtil.showStaticMessage("上报给后台有效的十分钟数据！！！！！！");
                        }
                        // 自动领取金豆
                        AndroidSchedulers.mainThread().scheduleDirect(() -> mPresenter.autoReceive(new INetCommCallback<AutoReceiveBean>() {
                            @Override
                            public void onResponse(AutoReceiveBean autoReceiveBean) {
                                if (TextUtils.isEmpty(autoReceiveBean.beans)) {
                                    return;
                                }
                                if (TextUtils.isDigitsOnly(autoReceiveBean.beans)) {
                                    int data = Integer.parseInt(autoReceiveBean.beans);
                                    if (data == 0) {
                                        return;
                                    }
                                }
                                ToastUtil.showStaticMessage(autoReceiveBean.beans + "金豆已到账");
                                TaskEvent event = new TaskEvent();
                                EventBus.getDefault().post(event);
                            }

                            @Override
                            public void onError(int code, String errDesc) {
                            }
                        }), 3, TimeUnit.MINUTES);
                    }
                }

                @Override
                public void onError(int code, String errDesc) {
                    if (mSettingConfig) {
                        ToastUtil.showStaticMessage("10分钟到了，上报数据失败！！！！！！");
                    }
                }
            }));
        }
    }

    public void saveReadedPageInfo() {
        int page = mSharedPreferences.getInt(KEY_PAGE_COUNT + "#" + UserUtils.getUserId(), 0);
        mSharedPreferences.edit().putInt(KEY_PAGE_COUNT + "#" + UserUtils.getUserId(), ++page).apply();
        if (page == 20 && mSettingConfig) {
            ToastUtil.showStaticMessage("当前阅读了20屏");
        }
    }

    public void reset() {
        mSharedPreferences.edit().putInt(KEY_PAGE_COUNT + "#" + UserUtils.getUserId(), 0).apply();
    }

    public void start() {
        if (mStart) {
            return;
        }
        mTimer.schedule(mTimerTask, VALIDE_READ_MINS, VALIDE_READ_MINS);
        mStart = true;
        if (mSettingConfig) {
            ToastUtil.showStaticMessage("进入阅读页计时");
        }
    }

    public void stop() {
        mTimer.cancel();
    }


}
